<template>
  <div :class="{ hasTagsView: needTagsView }" class="main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="商家名称" prop="storeName">
              <el-input v-model="queryParams.storeName" placeholder="请输入商家名" clearable @keyup.enter="handleQuery"
                        @blur="handleQuery"/>
            </el-form-item>
            <el-form-item label="省" prop="province">
              <el-select v-model="queryParams.provinceList" placeholder="请选择省" multiple
                         clearable filterable :reserve-keyword="false"
                         collapse-tags collapse-tags-tooltip @change="handleQuery();handleChange()">
                <el-option v-for="item in options" :key="item.value" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="市" prop="city">
              <el-select v-model="queryParams.cityList" placeholder="请选择市" multiple
                         clearable filterable :reserve-keyword="false"
                         collapse-tags collapse-tags-tooltip @change="handleQuery">
                <el-option v-for="item in cityOptions" :key="item.value" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="card-content" ref="cardRef">
      <template #header>
        <el-row :gutter="10" class="mb8" ref="headerRef">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['merchants:store:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                       v-hasPermi="['merchants:store:edit']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                       v-hasPermi="['merchants:store:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
                       v-hasPermi="['merchants:store:export']">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="storeList" :height="tableHeight" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column v-if="columns[0].visible" label="序号" width="50" type="index" align="center">
          <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[1].visible" label="店铺编号" align="center" prop="storeId" min-width="200"/>
        <el-table-column v-if="columns[2].visible" label="店铺名称" align="center" :show-overflow-tooltip="true"
                         prop="storeName" min-width="150"/>
        <el-table-column v-if="columns[3].visible" label="用户名称" align="center" prop="userId"
                         :show-overflow-tooltip="true" min-width="120"/>
        <el-table-column v-if="columns[4].visible" label="地址(经纬度)" align="center" prop="address"
                         :show-overflow-tooltip="true" min-width="120"/>
        <el-table-column v-if="columns[5].visible" label="省" align="center" prop="province" min-width="100">
          <template #default="scope">
            <el-text>{{ codeToText[scope.row.province] }}</el-text>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" label="市" align="center" prop="city" min-width="100">
          <template #default="scope">
            <el-text>{{ codeToText[scope.row.city] }}</el-text>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[7].visible" label="区" align="center" prop="area" min-width="100">
          <template #default="scope">
            <el-text>{{ codeToText[scope.row.area] }}</el-text>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[8].visible" label="街道" align="center" prop="street"  :show-overflow-tooltip="true" min-width="200"/>
        <el-table-column v-if="columns[9].visible" label="封面" align="center" prop="coverUrl" min-width="100">
          <template #default="scope">
            <ImagePreview
              :height="60"
              :preview-src-list="[scope.row.coverUrl]"
              :src="scope.row.coverUrl"
              :width="60"
            />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[10].visible" label="商家图标" align="center" prop="logoUrl" min-width="100">
          <template #default="scope">
            <ImagePreview
              :height="60"
              :preview-src-list="[scope.row.logoUrl]"
              :src="scope.row.logoUrl"
              :width="60"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" min-width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">{{
                scope.row.status === '0' ? '正常' : '禁用'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[11].visible" label="描述" align="center" prop="describe"
                         :show-overflow-tooltip="true" min-width="200"/>
        <el-table-column v-if="columns[12].visible" label="商家电话" align="center" prop="phone" min-width="150"/>
        <el-table-column v-if="columns[13].visible" label="评分" align="center" prop="score" min-width="80"/>
        <el-table-column label="操作" fixed="right" align="center" min-width="130"
                         class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button plain circle type="success" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['merchants:store:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button plain circle type="danger" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['merchants:store:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

    </el-card>
    <div class="page-content">
      <pagination
        v-show="total>0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改商家对话框 -->
    <el-drawer :title="drawer.title" v-model="drawer.visible" append-to-body close-on-click-modal>
      <el-form ref="storeFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商家名" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入商家名"/>
        </el-form-item>
        <el-form-item label="省/市/区" prop="selectedOptions">
          <el-cascader :options="options" v-model="form.selectedOptions" @change="handleChange" clearable/>
        </el-form-item>
        <el-form-item label="街道" prop="street">
          <el-input v-model="form.street" placeholder="请输入街道"/>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <imageUpload v-model="form.cover" :limit="1"/>
        </el-form-item>
        <el-form-item label="店铺图标" prop="logo">
          <imageUpload v-model="form.logo" :limit="1"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" active-value="0" inactive-value="1"/>
        </el-form-item>
        <el-form-item label="描述" prop="describe">
          <el-input v-model="form.describe" placeholder="请输入描述"/>
        </el-form-item>
        <el-form-item label="商家电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入商家电话"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Store" lang="ts">
import {listStore, getStore, delStore, addStore, updateStore} from '@/api/merchants/store';
import {StoreVO, StoreQuery, StoreForm} from '@/api/merchants/store/types';
import useSettingsStore from "@/store/modules/settings";
import {useTableHeight} from "@/utils/useTableHeight";
import {regionData, codeToText,} from 'element-china-area-data'

/*计算表格高度*/
const cardRef = ref<HTMLElement | null>(null);
const headerRef = ref<any>(null);
const {tableHeight} = useTableHeight(cardRef, [headerRef]);
const settingsStore = useSettingsStore()
const needTagsView = computed(() => settingsStore.tagsView);
const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const storeList = ref<StoreVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 列显隐信息
const columns = ref<FieldOption[]>([
  {key: 0, label: `序号`, visible: true, children: []},
  {key: 1, label: `店铺编号`, visible: false, children: []},
  {key: 2, label: `店铺名称`, visible: true, children: []},
  {key: 3, label: `用户名称`, visible: true, children: []},
  {key: 4, label: `地址(经纬度)`, visible: true, children: []},
  {key: 5, label: `省`, visible: true, children: []},
  {key: 6, label: `市`, visible: true, children: []},
  {key: 7, label: `区`, visible: true, children: []},
  {key: 8, label: `街道`, visible: true, children: []},
  {key: 9, label: `封面`, visible: true, children: []},
  {key: 10, label: `商家图标`, visible: true, children: []},
  {key: 11, label: `描述`, visible: true, children: []},
  {key: 12, label: `商家电话`, visible: true, children: []},
  {key: 13, label: `评分`, visible: true, children: []},
]);

const queryFormRef = ref<ElFormInstance>();
const storeFormRef = ref<ElFormInstance>();

const drawer = reactive<DrawerOption>({
  visible: false,
  title: ''
});

const initFormData: StoreForm = {
  storeId: undefined,
  storeName: undefined,
  address: undefined,
  selectedOptions: undefined,
  province: undefined,
  city: undefined,
  area: undefined,
  street: undefined,
  cover: undefined,
  logo: undefined,
  status: undefined,
  describe: undefined,
  phone: undefined,
  score: undefined,
}
const data = reactive<PageData<StoreForm, StoreQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    storeName: undefined,
    address: undefined,
    province: undefined,
    provinceList: undefined,
    city: undefined,
    cityList: undefined,
    area: undefined,
    status: undefined,
    areaList: undefined,
    street: undefined,
    score: undefined,
    params: {}
  },
  rules: {
    storeId: [
      {required: true, message: "商家编号不能为空", trigger: "blur"}
    ],
    storeName: [
      {required: true, message: "商家名称不能为空", trigger: "blur"}
    ],
    selectedOptions: [
      {required: true, message: "省/市/区不能为空", trigger: "blur"}
    ],
    cover: [
      {required: true, message: "封面url不能为空", trigger: "blur"}
    ],
    logo: [
      {required: true, message: "商家图标url不能为空", trigger: "blur"}
    ],
    phone: [
      {required: true, message: "商家电话不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/*省市区数据*/
const options = ref(regionData);
/*市级数据*/
const cityOptions = ref(getCityData(options.value))

function getCityData(data) {
  let municipalData = [];

  function traverse(data) {
    data.forEach(item => {
      if (item.children) {
        municipalData.push(item);
        traverse(item.children);
      }
    });
  }

  traverse(data);
  return municipalData;
}

const handleChange = () => {
  console.log(cityOptions.value);
}

/** 查询商家列表 */
const getList = async () => {
  loading.value = true;
  const res = await listStore(queryParams.value);
  storeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  drawer.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  storeFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: StoreVO[]) => {
  ids.value = selection.map(item => item.storeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  drawer.visible = true;
  drawer.title = "添加商家";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: StoreVO) => {
  reset();
  const _id = row?.storeId || ids.value[0]
  const res = await getStore(_id);
  Object.assign(form.value, res.data);
  /*省市区列表赋值*/
  form.value.selectedOptions = [form.value.province, form.value.city, form.value.area];
  drawer.visible = true;
  drawer.title = "修改商家";
}

/** 提交按钮 */
const submitForm = () => {
  storeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      /*提取省市区列表*/
      form.value.province = form.value.selectedOptions[0];
      form.value.city = form.value.selectedOptions[1];
      form.value.area = form.value.selectedOptions[2];
      if (form.value.storeId) {
        await updateStore(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addStore(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      drawer.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: StoreVO) => {
  const _ids = row?.storeId || ids.value;
  await proxy?.$modal.confirm('是否确认删除商家编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delStore(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('merchants/store/export', {
    ...queryParams.value
  }, `store_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
